/*
 * Copyright (C) 2008 GeoScheduler team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */
package org.geoscheduler.android.activities;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.geoscheduler.android.R;
import org.geoscheduler.android.tools.DBHelper;
import org.geoscheduler.model.Event;
import org.geoscheduler.model.Tag;
import org.geoscheduler.model.Event.AlertType;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/**
 * Alert popup activity shows up when event time/place/tag occurred 
 * 
 * @author paja
 * @author srakyi
 */
public class AlertPopup extends Activity {
	
	public static final int SNOOZE_MINUTES = 5;
	
	public static final String PAR_EVENT_ID = ".event_id";
	
	private static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy HH:mm");

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		initView();
	}
	
	/**
	 * Take care of setting up AlertPopup layout
	 */
	protected void initView() {
		setContentView(R.layout.alert_pop_up);
		
		Bundle extras = getIntent().getExtras();
		final long eventId = extras.getLong(AlertPopup.class.getName() + AlertPopup.PAR_EVENT_ID, 0);

		Event event = new Event();
		try {
			SQLiteDatabase db = DBHelper.openDB(this);
			if ((!DBHelper.fetchInst(db, eventId, event)) || (event == null)) {
				throw new Exception("Event fetch failed."); 
			}
			event.setTags(DBHelper.fetchTags(db, eventId));
			db.close();
		} catch (Exception e) {
			new AlertDialog.Builder(this) 
		     .setTitle(R.string.label_error) 
		     .setMessage(R.string.msg_err_event_load_failed) 
		     .setPositiveButton(R.string.label_ok, new DialogInterface.OnClickListener() { 

		          public void onClick(DialogInterface dialog, int whichButton) {
		        	  
		          } 
		     }).show();
//			finish();
		}
		final Event finalEvent = event;
		
		((TextView)findViewById(R.id.alert_eventtitle)).setText(event.getTitle());
		
		((TextView)findViewById(R.id.alert_eventwhere)).setText("");
		
		if (event.getAlertTypeEnum() == AlertType.LOCATION_OR_TIME
				|| event.getAlertTypeEnum() == AlertType.LOCATION_TIME
				|| event.getAlertTypeEnum() == AlertType.LOCATION_XOR_TIME
				|| event.getAlertTypeEnum() == AlertType.TAG_AND_TIME
				|| event.getAlertTypeEnum() == AlertType.TAG_OR_TIME
				|| event.getAlertTypeEnum() == AlertType.TIME) {
			StringBuilder when = new StringBuilder();
			if (event.getTimeFrom() != null) {
				when.append(AlertPopup.DATE_FORMAT.format(event.getTimeFrom()));
			}
			if (event.getTimeTo() != null) {
				if (when.length() > 0) {
					when.append(" - ");
				}
				when.append(AlertPopup.DATE_FORMAT.format(event.getTimeTo()));
			}
			if (when.length() > 0) {
				((TextView)findViewById(R.id.alert_eventwhen)).setText(when.toString());
			} else {
				((TextView)findViewById(R.id.alert_eventwhen)).setText(getText(R.string.label_anytime));
			}
		} else {
			((TextView)findViewById(R.id.alert_eventwhen)).setText(getText(R.string.label_anytime));
		}
		
		
		((TextView)findViewById(R.id.alert_eventdescription)).setText(event.getDescription());
		
		String tagStr = "";
		if (event.getTags() != null) {
			StringBuilder tags = new StringBuilder();
			boolean first = true;
			for (Tag t : event.getTags()) {
				if (!first) {
					tags.append(", ");
				} else {
					first = false;
				}
				tags.append(t.getName());
			}
			
			if (tags.length() > 0) {
				tagStr = "(" + tags.toString() + ")";
			}
		}
		((TextView)findViewById(R.id.alert_eventtags)).setText(tagStr);
		
		/* Edit button */
		Button btnEdit = (Button) findViewById(R.id.alert_button_edit);
		btnEdit.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				
		        Intent editEvent = new Intent(AlertPopup.this, EditEvent.class);
		        editEvent.putExtra("org.geoscheduler.android.item.id", eventId);

				startActivity(editEvent);
				
				AlertPopup.this.finish();
			}
		});
		
		/* Snooze button */
		Button btnSnooze = (Button) findViewById(R.id.alert_button_snooze);
		btnSnooze.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				try {
					// FIXME [srakyi] this must be completely rewritten ..
					
					Calendar cal = Calendar.getInstance();
					cal.setTime(new Date());
					cal.add(Calendar.MINUTE, AlertPopup.SNOOZE_MINUTES);
					finalEvent.setTimeFrom(cal.getTime());
					
					if (finalEvent.getTimeTo().before(cal.getTime())) {
						cal.add(Calendar.MINUTE, 30);
						finalEvent.setTimeTo(cal.getTime());
					}
					
					SQLiteDatabase db = DBHelper.openDB(AlertPopup.this); 
					if (DBHelper.storeInst(db, finalEvent) < 0) {
						throw new Exception("Store event failed.");
					}
				} catch (Exception e) {
					(new AlertDialog.Builder(AlertPopup.this)).
						setIcon(R.drawable.stop).
						setTitle(R.string.label_error).
						setMessage(R.string.evpopup_msg_err_snooze_failed).
						setPositiveButton(R.string.label_ok, null).
						create().
						show();
				}
				
				AlertPopup.this.finish();
			}
		});
		
		/* Gotcha button */
		Button btnGotcha = (Button) findViewById(R.id.alert_button_gotcha);
		
		// FIXME [srakyi] localize me!
		List<String> rndGotcha = new ArrayList<String>(5);
		rndGotcha.add("Gotcha!");
		rndGotcha.add("Yeah, right!");
		rndGotcha.add("Done");
		rndGotcha.add("Ok, Ok!");
		rndGotcha.add("I've got it!");
		
		btnGotcha.setText(rndGotcha.get((int)Math.floor((Math.random() * rndGotcha.size()))));
		
		btnGotcha.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				try {
					// FIXME [srakyi] this must be completely rewritten ..
					
					finalEvent.setAlertTypeEnum(Event.AlertType.NONE);
					
					SQLiteDatabase db = DBHelper.openDB(AlertPopup.this);
					if (DBHelper.storeInst(db, finalEvent) < 0) {
						throw new Exception("Store event failed.");
					}
				} catch (Exception e) {
					(new AlertDialog.Builder(AlertPopup.this)).
						setIcon(R.drawable.stop).
						setTitle(R.string.label_error).
						setMessage(R.string.evpopup_msg_err_snooze_failed).
						setPositiveButton(R.string.label_ok, null).
						create().
						show();
				}
				
				AlertPopup.this.finish();
			}
		});
	}
}
